﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CalemShop
{
    public partial class FrmCustomer : Form
    {
        private DataTable sr = new DataTable();
        private bool isAddNew = false;
        AutoCompleteStringCollection serialsList;
        public FrmCustomer()
        {
            InitializeComponent();
            sr.Columns.Add("customerId", Type.GetType("System.Int32"));
            sr.Columns.Add("customerName", Type.GetType("System.String"));
            sr.Columns.Add("phone", Type.GetType("System.String"));
            sr.Columns.Add("email", Type.GetType("System.String"));
            sr.Columns.Add("facebook", Type.GetType("System.String"));
            sr.Columns.Add("serial", Type.GetType("System.String"));
            sr.Columns.Add("point", Type.GetType("System.Int32"));
        }

        private void FrmCustomer_Load(object sender, EventArgs e)
        {
            bindingSource1.DataSource = sr;
            serialsList = new AutoCompleteStringCollection();
            for (int i = 0; i < 1000; i++)
            {
                string snum = i.ToString();
                while (snum.Length < 4)
                {
                    snum = "0" + snum;
                }

                serialsList.Add("CW." + snum);
                serialsList.Add("CB." + snum);
                serialsList.Add("CG." + snum);
            }

            txtSearch.AutoCompleteCustomSource = Database.getCustomerDataCollection();

        }

        private void btNew_Click(object sender, EventArgs e)
        {
            sr.Clear();
            addNew();
        }

        private void addNew()
        {
            try
            {
                DataRow r = sr.NewRow();
                sr.Rows.Add(r);
                isAddNew = true;
                point.ReadOnly = false;
            }
            catch (Exception)
            {
            }
        }


        private void grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            try
            {
                TextBox prodCode = e.Control as TextBox;
                if (prodCode != null)
                {
                    int index = grid.CurrentCell.ColumnIndex;
                    if (index == serial.Index)
                    {
                        prodCode.AutoCompleteMode = AutoCompleteMode.Suggest;
                        prodCode.AutoCompleteCustomSource = serialsList;
                        prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    }

                }
            }
            catch (Exception) { }
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (sr.Rows.Count <= 0)
                {
                    return;
                }

                if (!checkValidData())
                {
                    return;
                }
                DataRow r = sr.Rows[0];
                Customer cs = new Customer();
                cs.customerName = (string)r["customerName"];
                if (r["phone"].GetType() != Type.GetType("System.DBNull"))
                {
                    cs.phone = (string)r["phone"];
                }

                if (r["email"].GetType() != Type.GetType("System.DBNull"))
                {
                    cs.email = (string)r["email"];
                }

                if (r["facebook"].GetType() != Type.GetType("System.DBNull"))
                {
                    cs.facebook = (string)r["facebook"];
                }

                if (r["serial"].GetType() != Type.GetType("System.DBNull"))
                {
                    cs.serial = (string)r["serial"];
                }

                //if (r["point"].GetType() != Type.GetType("System.DBNull"))
                //{
                //    Int32.TryParse(r["point"].ToString(), out cs.point);
                //}

                if (Database.insertCustomer(cs) > 0)
                {
                    sr.Clear();
                    isAddNew = false;
                    point.ReadOnly = true;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void grid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == customerName.Index)
                {
                    DataGridViewCell cell = grid[e.ColumnIndex, e.RowIndex];
                    if (cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString()))
                    {
                        cell.ErrorText = "Tên khách hàng không bỏ trống";
                    }
                    else
                    {
                        cell.ErrorText = string.Empty;
                    }
                }
                else if (e.ColumnIndex == phone.Index)
                {
                    DataGridViewCell cell = grid[e.ColumnIndex, e.RowIndex];
                    if (cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString()))
                    {
                        cell.ErrorText = "Phone không bỏ trống";
                    }
                    else
                    {
                        cell.ErrorText = string.Empty;
                    }
                }
            }
        }

        private bool checkValidData()
        {
            DataGridViewCell cellCusName = grid[customerName.Index, 0];
            if (cellCusName.Value == null || string.IsNullOrEmpty(cellCusName.Value.ToString()))
            {
                cellCusName.ErrorText = "Tên khách hàng không bỏ trống";
                return false;
            }
            cellCusName.ErrorText = string.Empty;

            DataGridViewCell cellPhone = grid[phone.Index, 0];
            if (cellPhone.Value == null || string.IsNullOrEmpty(cellPhone.Value.ToString()))
            {
                cellPhone.ErrorText = "Số phone không bỏ trống";
                return false;
            }


            cellPhone.ErrorText = string.Empty;
            return true;

        }


        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DataTable t = Database.searchCustomer(txtSearch.Text);
                if (t != null)
                {
                    sr = t;
                    bindingSource1.DataSource = sr;
                    bindingSource1.ResetBindings(true);
                    grid.Focus();
                    isAddNew = false;
                    point.ReadOnly = true;
                }
            }
        }


        private void grid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (!e.Row.IsNewRow)
            {
                try
                {
                    DataRow r = sr.Rows[e.Row.Index];
                    int id = 0;
                    Int32.TryParse(r["customerId"].ToString(), out id);
                    Database.deleteCustomer(id);
                    isAddNew = false;
                }
                catch (Exception ex) { }
            }
        }

        private void grid_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    int index = grid.CurrentRow.Index;
                    DataRow r = sr.Rows[index];
                    int id = 0;
                    Int32.TryParse(r["customerId"].ToString(), out id);
                    if (Database.deleteCustomer(id))
                    {
                        grid.Rows.RemoveAt(index);
                    }

                }
                else if (e.KeyCode == Keys.Enter && grid.CurrentCell != null && grid.CurrentCell.ColumnIndex == serial.Index)
                {
                    Point p = grid.GetCellDisplayRectangle(grid.CurrentCell.ColumnIndex, grid.CurrentCell.RowIndex, false).Location;
                    contextMenuSerials.Show(grid, p);
                    e.Handled = true;
                }
            }
            catch (Exception ex) { }
        }

        private void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (!isAddNew)
                {
                    DataRow r = sr.Rows[e.RowIndex];
                    DataGridViewRow rv = grid.Rows[e.RowIndex];
                    if (MessageBox.Show("Lưu lại thay đổi hay không ?", "Xác nhận", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        r.CancelEdit();
                        return;
                    }

                    Customer cs = new Customer();
                    if (r["customerName"].GetType() == Type.GetType("System.DBNull"))
                    {
                        rv.ErrorText = "Tên khách hàng không hợp lệ";
                        return;
                    }


                    if (r["phone"].GetType() == Type.GetType("System.DBNull"))
                    {
                        rv.ErrorText = "số phone không hợp lệ";
                        return;
                    }


                    if (r["customerName"].GetType() != Type.GetType("System.DBNull"))
                    {
                        cs.customerName = (string)r["customerName"];
                        rv.ErrorText = string.Empty;
                    }


                    if (r["phone"].GetType() != Type.GetType("System.DBNull"))
                    {
                        cs.phone = (string)r["phone"];
                        rv.ErrorText = string.Empty;
                    }

                    if (r["email"].GetType() != Type.GetType("System.DBNull"))
                    {
                        cs.email = (string)r["email"];
                    }

                    if (r["facebook"].GetType() != Type.GetType("System.DBNull"))
                    {
                        cs.facebook = (string)r["facebook"];
                    }

                    if (r["serial"].GetType() != Type.GetType("System.DBNull"))
                    {
                        cs.serial = (string)r["serial"];
                    }

                    //if (r["point"].GetType() != Type.GetType("System.DBNull"))
                    //{
                    //    Int32.TryParse(r["point"].ToString(), out cs.point);
                    //}

                    cs.customerId = (int)r["customerId"];
                    Database.updateCustomer(cs);
                }

            }
            catch (Exception ee) { MessageBox.Show(ee.Message); }

        }

        private void mnSetSerial_Click(object sender, EventArgs e)
        {
            if (grid.CurrentCell != null)
            {
                grid.CurrentCell.ReadOnly = false;
                grid.BeginEdit(true);
            }
        }

        private void btShowAll_Click(object sender, EventArgs e)
        {
            DataTable t = Database.getAllCustomer();
            if (t != null)
            {
                sr = t;
                bindingSource1.DataSource = sr;
                bindingSource1.ResetBindings(true);
                grid.Focus();
                isAddNew = false;
                point.ReadOnly = true;
                string[] sqls = new string[t.Rows.Count];
                int index = 0;
                foreach (DataRow r in t.Rows)
                {
                    var serial = r["serial"];
                    if (serial == null || string.IsNullOrEmpty(serial.ToString()))
                    {
                        serial = string.Empty;
                    }

                    int p = 0;
                    if (r["totalPaid"] == null)
                    {
                        int.TryParse(r["totalPaid"].ToString(), out p);
                    }

                    DateTime d = (DateTime)r["createTime"];
                     sqls[index++] = "insert into customer_new(customerName,phone,point,serial,createTime) values('" + r["customerName"] + "','" + r["phone"] + "'," +
                        p + ",'" + serial + "','" + d.ToString("yyyy-MM-dd HH:mm:ss") + "')";

                   
                }

                Database.executeQuerys(sqls);
            }
        }

        private void FrmCustomer_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                FrmMain frmMain = (FrmMain)this.MdiParent;
                frmMain.frmCustomer = null;
            }
            catch (Exception) { }
        }

    }// class
}
